import React, { Component } from 'react';
import { StyleSheet, TouchableWithoutFeedback, Text, View, Animated, Keyboard } from 'react-native';
import { Button } from '../touchableView';
import screen from '../../utils/screen';
import _ from 'lodash'

class Dialog extends Component {
    defaultState = {
        title: '',
        content: null,
        button: [],
        headerStyle: {},
        titleStyle: {},
        contentStyle: {},
        containerStyle: {},
        footerStyle: {},
        btnDirection: 'row',
        clickOnMask: false,
        closeOnMask: false
    };

    constructor(props) {
        super(props);
        this.state = {
            ...this.defaultState,
            boxWidth: screen.width,
            boxHeight: screen.height,
            zIndex: new Animated.Value(-98),
            maskOpacity: new Animated.Value(0),
            boxOpacity: new Animated.Value(0), // 透明度初始值
            boxBounce: new Animated.Value(0.8) // 大小初始值
        };

        this.showDialog = this.showDialog.bind(this);

        this._animateHandler = null;
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (_.isEqual(this.props, nextProps) && _.isEqual(this.state, nextState)) {
            return false;
        }
        return true;
    }

    showDialog(config = {}) {
        Keyboard.dismiss();
        const defaultBtn = {
            contentStyle: {},
            disabledContentStyle: {},
            containerStyle: {},
            fontStyle: {
                // 设置 botton 的默认颜色
                color: '#15BCE6'
            },
            disabledFontStyle: {},
            disabled: false,
            text: '确认',
            onPress: null,
            pressHide: true,
            tag: 'confirm'
        }; // 默认按钮
        const cancelBtn = {
            text:'取消',
            onPress:null,
            pressHide: true,
        }

        const defaultConfig = {
            title: '温馨提示',
            content: null,
            button: [defaultBtn,cancelBtn],
            headerStyle: {},
            titleStyle: {},
            contentStyle: {},
            footerStyle: {},
            containerStyle: {},
            onClose: null
        }; // 默认参数

        let option = _.assign({}, defaultConfig, config);

        if (option.button) {
            // 如果为多个 第一个按钮默认为 灰色 (其大多为 "取消" 文案)
            let firstButtonStyle = { fontStyle: { color: '#999999' } };
            if (option.button.length !== 2) {
                firstButtonStyle = {};
            }
            for (let i = 0; i < option.button.length; i++) {
                let btn = _.assign({}, defaultBtn, option.button[i], i === 0 && firstButtonStyle);
                option.button[i] = btn;
            }
        }

        this.setState({
            ...option,
            boxWidth: screen.width,
            boxHeight: screen.height
        });

        this.state.zIndex.setValue(99);

        this._animateHandler = Animated.parallel([
            Animated.timing(this.state.boxOpacity, {
                toValue: 1,
                duration: 150,
                useNativeDriver: true
            }),
            Animated.spring(this.state.boxBounce, {
                toValue: 1,
                duration: 100,
                useNativeDriver: true
            }),
            Animated.timing(this.state.maskOpacity, {
                toValue: 1,
                duration: 200,
                useNativeDriver: true
            })
        ]);

        this._animateHandler.start(({ finished }) => {
            if (finished && option.duration && Number.isFinite(option.duration)) {
                this._hideTimeout = setTimeout(() => {
                    for (let i = 0; i < option.button.length; i++) {
                        let btn = _.assign({}, defaultBtn, option.button[i]);
                        option.button[i] = btn;
                    }
                    this._closeWithNoPress();
                }, option.duration);
            }
        });
    }

    performHiding = () => {
        this._animateHandler = Animated.parallel([
            Animated.spring(this.state.boxBounce, {
                toValue: 0.8,
                duration: 80,
                useNativeDriver: true
            }),
            Animated.timing(this.state.boxOpacity, {
                toValue: 0,
                duration: 200,
                useNativeDriver: true
            }),
            Animated.timing(this.state.maskOpacity, {
                toValue: 0,
                duration: 80,
                delay: 30,
                useNativeDriver: true
            }),
            Animated.timing(this.state.zIndex, {
                toValue: -99,
                useNativeDriver: true
            })
        ]);

        this._animateHandler.start(({ finished }) => {
            if (finished) {
                this.setState({
                    ...this.defaultState
                });
            }
        });
        if (this.state.onClose) {
            this.state.onClose();
        }
    };

    hideDialog = (cb, hide = true) => {


        if (this._hideTimeout) {
            clearTimeout(this._hideTimeout);
            this._hideTimeout = null;
        }
        if (hide) {
            this.performHiding();
        }

        cb && cb();
        if (hide && this.props.onHide) {
            this.props.onHide();
        }
    };

    _findOncloseOptionButton = () => {
        const option = this.state;
        if (option.button) {
            let targetButton;
            if (option.button.length !== 1) {
                targetButton = option.button.find(btn => btn.onClose);
            }
            if (!targetButton) {
                targetButton = option.button[0];
            }
            return targetButton;
        }
        return null;
    };

    _closeWithNoPress = () => {
        if (this._findOncloseOptionButton()) {
            this.hideDialog(this._findOncloseOptionButton().onPress, this._findOncloseOptionButton().pressHide);
        } else {
            this.hideDialog();
        }
    };

    _handleMaskPress = () => {
        if (this.state.closeOnMask) {
            this.hideDialog();
            if (this.state.onClose) {
                this.state.onClose();
            }
        } else if (this.state.clickOnMask) {
            this._closeWithNoPress();
            if (this.state.onClose) {
                this.state.onClose();
            }
        }
    };

    render() {
        const {
            zIndex,
            maskOpacity,
            boxOpacity,
            boxBounce,
            title,
            button,
            content,
            headerStyle,
            titleStyle,
            contentStyle,
            containerStyle,
            footerStyle,
            btnDirection,
            boxWidth,
            boxHeight
        } = this.state;


        return (
            <Animated.View style={[styles.layer, { zIndex: zIndex, width: boxWidth, height: boxHeight }]}>
                <TouchableWithoutFeedback onPress={this._handleMaskPress}>
                    <Animated.View style={[styles.mask, { opacity: maskOpacity }]} />
                </TouchableWithoutFeedback>
                <Animated.View
                    style={[
                        styles.container,
                        {
                            backgroundColor: contentStyle.backgroundColor || 'white',
                            width: screen.width - screen.PIXEL_180, // 默认宽度使用百分比会好很多, width - 100
                            opacity: boxOpacity,
                            transform: [{ scale: boxBounce }],
                            maxWidth: contentStyle.maxWidth,
                            ...containerStyle
                        }
                    ]}
                >
                    {title ? (
                        <View style={[styles.header, headerStyle]}>
                            <Text style={[styles.title, titleStyle]}>{title}</Text>
                        </View>
                    ) : null}

                    {/*<View style={[styles.content, contentStyle]}>{realContent}</View>*/}

                    <View style={[styles.footer, footerStyle, { flexDirection: 'row',justifyContent:'center' }]}>
                        {button.map((d, i) => {
                            return (
                                <Button
                                    key={'btn_' + i}
                                    contentStyle={[
                                        styles.buttonBox,
                                        i === 0 ? {
                                            backgroundColor:'#0D80FC'
                                        } : {
                                            borderWidth:0.3,borderColor:'#0D80FC',marginLeft:screen.PIXEL_20
                                        },
                                        d.contentStyle,
                                        d.disabled ? d.disabledContentStyle : {}
                                    ]}
                                    fontStyle={[
                                        styles.buttonTxt,
                                        i === 0 ? {
                                            color:'#fff'
                                        } : {
                                            color:'#0D80FC'
                                        },
                                        // d.fontStyle,
                                        // d.disabled ? d.disabledFontStyle : {}
                                    ]}
                                    disabled={false}
                                    tag={d.tag}
                                    onPress={() => this.hideDialog(d.onPress, d.pressHide)}
                                    noET={true}
                                >
                                    {d.text}
                                </Button>
                            );
                        })}
                    </View>
                </Animated.View>
            </Animated.View>
        );
    }
}

const styles = StyleSheet.create({
    layer: {
        position: 'absolute',
        top: 0,
        left: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    mask: {
        width: '100%',
        height: '100%',
        position: 'absolute',
        top: 0,
        left: 0,
        backgroundColor: 'rgba(0,0,0,0.5)'
    },
    container: {
        borderRadius: screen.PIXEL_16,
        flexDirection: 'column',
        backgroundColor: '#fff'
    },
    header: {
        marginTop: 34,marginBottom:34,
        justifyContent: 'center',
        alignItems: 'center'
    },
    title: {
        color: '#333333',
        fontSize: 16,fontWeight:'500'
    },
    footer:{
        paddingBottom:screen.PIXEL_40
    },
    content: {
        paddingTop: 12,
        paddingBottom: 34,
        paddingHorizontal: 20
    },
    buttonBox: {
        height: screen.PIXEL_60,width:screen.PIXEL_160,
        borderRadius: screen.PIXEL_30
    },
    buttonTxt: {
        fontSize: 12,
        color: '#fff'
    }
});

export default Dialog

/**
 * 用法
 import {dialogRef} from 'xxx/app';
 dialogRef.showDialog({
    // 弹窗标题 ps 默认:温馨提示 null:隐藏头部
    title: null,
    // 弹窗主体
    content: <Text>内容内容内容</Text>,
    // 底部按钮 ps 默认:单按钮 null:隐藏底部
    button: [
        {
            // 按钮文本
            text: '取消',
            // 按钮容器样式
            contentStyle: {},
            // 按钮不可点击状态容器样式
            disabledContentStyle: {},
            // 按钮文本样式
            fontStyle: {},
            // 按钮不可点击状态文本样式
            disabledFontStyle: {}
        },
        {
            text: '确定',
            // 按钮点击事件回调
            onPress: () => {
                alert('xxx');
            },
            // 按钮是否可点击
            disabled: true,
            // 按钮事件是否关闭弹窗
            pressHide: false,
            // 按钮标签
            tag: 'cancel',
            // 当设置 duration 自动关闭时, 或者 clickOnMask 时, 如果只一个 button, 会使用该 button 的 onPress 作为回调, 如果有多个 button, 会使用 onClose 为 true 的 onPress 作为回调
             onClose: false
        }
    ],
    // 头部容器样式
    headerStyle: {},
    // 标题样式
    titleStyle: {},
    // 内容容器样式
    contentStyle: {},
    // 容器样式
    containerStyle:{}
    // 底部容器样式
    footerStyle: {},
    // 按钮排列方向
    btnDirection: 'column',
    // 延时关闭, 单位为毫秒, 无默认值
    duration: null
    // 点击非 dialog body 触发按钮事件
    clickOnMask,
    // 点击非 dialog body 区域关闭 dialog
    closeOnMask
});
 */


